class OsnFriend {
    func fromJson(_ json:[String:Any]) -> DMCCFriend {
        let u = DMCCFriend()
        u.userId = json["userID"] as? String ?? ""
        u.friendId = json["friendID"] as? String ?? ""
        u.alias = json["remarks"] as? String ?? ""
        u.state = OsnFriendState(rawValue: json["state"] as? Int ?? 1)
        return u
    }
    func getFriendInfo(_ osnId:String) -> DMCCFriend? {
        if let friend = dbFriend.getFriendInfo(osnId) {
            return friend
        }
        Task { await gidService.refreshId(IdsType.friend, osnId) }
        return nil
    }
    func setFriendInfo(_ info:DMCCFriend) ->Bool {
        return dbFriend.addFriendInfo(info)
    }
    func delFriendInfo(_ osnId:String) ->Bool {
        return dbFriend.delFriendInfo(osnId)
    }
    func fetchFriendInfo(_ osnId:String) async ->DMCCFriend? {
        let data:[String:Any] = ["friendID": osnId]
        guard let info = await gimService.imRequestService("GetFriendInfo", data) else {return nil}
        guard let res = gimService.getResult(info) else {return nil}
        let friendInfo = fromJson(res)
        _ = setFriendInfo(friendInfo)
        if !friendInfo.alias.isEmpty {
            updateRelateUserInfo(osnId, res)
        }
        return friendInfo
    }
    func fetchFriendList() async ->[String] {
        guard let res = await gimService.imRequestService("GetFriendList", nil) else {return []}
        guard let res = gimService.getResult(res) else {return []}
        guard let res = res["friendList"] as? [String] else {return []}
        var array = res
        if array.contains(gosnUser.myId()) {
            array = array.filter { $0 != gosnUser.myId() }
        }
        for osnId in array {
            if getFriendInfo(osnId) == nil {
                _ = await fetchFriendInfo(osnId)
            }
        }
        
        return array
    }
    func getFriendList()->[DMCCFriend]{
        return dbFriend.listFriendInfo()
    }
    
    func getBlackList()->[DMCCFriend]{
        return dbFriend.listFriends(state: OsnFriendState.Blacked.rawValue)
    }
    
    func deleteFriend(_ osnId:String) async ->Bool {
//        guard await gimService.imRequestService("DelFriend", ["friendID": osnId]) != nil else {return false}
        
        guard let res = await gimService.imRequestService("DelFriend", ["friendID": osnId]) else {return false}
        
        _ = gosnConversation.deleteConversation(osnId)
        _ = gosnMessage.clearMessage(osnId)
        let isDel = delFriendInfo(osnId)
//        updateRelateUserInfo(osnId, ["state": OsnFriendState.Deleted.rawValue]) //删了又更新回来了
        return true
    }
    func blackFriend(_ friendId:String, _ isBlacked:Bool) async ->Bool {
        let state = if isBlacked {OsnFriendState.Blacked.rawValue}else{OsnFriendState.Normal.rawValue}
        let state2 = if isBlacked {OsnFriendState.Blacked}else{OsnFriendState.Normal}
        guard await gimService.imRequestService("SetFriendInfo", ["friendID": friendId, "state": state ]) != nil else {return false}
        if let info = getFriendInfo(friendId){
            info.state = state2
            _ = setFriendInfo(info)
            updateRelateUserInfo(friendId, ["state": state])
        }
        return true
    }
    func inviteFriend(_ userId:String, _ reason:String) async ->Bool {
        guard let res = await gimService.imRequest("AddFriend", userId, ["reason":reason]) else {return false}
        return gimService.isSuccess(res)
    }
    func isFriend(_ osnId:String) ->Bool {
        return getFriendInfo(osnId) != nil
    }
    func isBlacked(_ osnId:String) ->Bool {
        guard let u = getFriendInfo(osnId) else {return false}
        return u.state == OsnFriendState.Blacked
    }
    func setAlias(_ osnId:String, _ alias:String) async ->Bool {
        guard await gimService.imRequestService("SetFriendInfo",[ "friendID": osnId, "remarks": alias ]) != nil else {return false}
        if let friend = getFriendInfo(osnId){
            friend.alias = alias
            _ = setFriendInfo(friend)
        }
        updateRelateUserInfo(osnId, ["alias": alias])
        return true
    }
    func updateRelateUserInfo(_ osnId:String, _ info:[String:Any]){
        let user = gosnUser.getUserInfoDefault(osnId)
        if(info.keys.contains("alias")){
            user.friendAlias = info["alias"] as? String ?? ""
        }
        if(info.keys.contains("state")){
            user.state = info["state"] as? Int ?? 0
        }
        _ = gosnUser.setUserInfo(user)
    }
    func refreshFriend() async {
        await gimService.syncFriend()
    }
    
    
    func getAddFreiendCount () -> Int {
    return UserDefaults.standard.integer(forKey: "kAddFreiendCount")
    }
        
    func setAddFreiendCount () {
    UserDefaults.standard.setValue(1, forKey: "kAddFreiendCount")
    geventService.post(OsnEvent.FriendRequestUpdated, "")
    }
        
    func delAddFreiendCount () {
    UserDefaults.standard.setValue(0, forKey: "kAddFreiendCount")
    geventService.post(OsnEvent.FriendRequestUpdated, "")
    }
}
let gosnFriend = OsnFriend()
